var modifyOrAddFlag;
var bundleId = "";
$(document)
		.ready(
				function() {
					// 导入
					$('#import_link').window({
						width : 465,
						modal : true,
						minimizable : false,
						maximizable : false,
						collapsible : false
					});
					$('#import_link').window('close'); // 关闭窗口

					$("#selFileBtn").click(function(e) {
						e.preventDefault();
						// $("#file").click();
					});

					$("#import_form").delegate(
							"#file",
							"change",
							function() {
								var filePath = $('#file').val();
								if (filePath != ""
										&& filePath.indexOf("\\") != -1) {
									$("#fileName").val($('#file').val());
									var bundleName = filePath.substring(
											filePath.lastIndexOf("\\") + 1,
											filePath.length);
									$("#bundleName").val(bundleName);
								} else {
									$("#fileName").val($('#file').val());
									$("#bundleName").val($('#file').val());
								}
								// clearAutofillStyle();
							});

					bundleId = getUrlParam('bundleId');
					if (bundleId == null || bundleId == '') {
						$('#win').window('close');
					} else {
						showBundleDetail(bundleId);
					}

					$("#datagrid")
							.datagrid(
									{
										url : BASE_URL_API
												+ '/baseServiceManagement/findBundleInfos?v='
												+ Math.random(),
										method : 'get',
										autoRowHeight : true,
										singleSelect : true,
										striped : true,
										nowrap : false,
										pageSize : 20,
										pageList : [ 10, 20, 50, 100 ],
										columns : [ [
												{
													field : 'id',
													title : 'Id',
													width : 10,
													align : 'center'
												},
												{
													field : 'name',
													title : 'Bundle名称',
													width : 80,
													align : 'left',
													formatter : function(value,
															rowData, rowIndex) {
														return '<a href="javascript:void(0)" class="default_btn fl" onclick="showBundleDetail('
																+ rowData.id
																+ ""
																+ ')">'
																+ value
																+ '</a>';

													}
												},
												{
													field : 'version',
													title : '版本号',
													width : 15,
													align : 'center'
												},
												{
													field : 'state',
													title : '状态',
													width : 15,
													align : 'center'
												},
												{
													field : 'isCore',
													title : '是否是内核',
													width : 15,
													align : 'center',
													formatter : function(value,
															rowData, rowIndex) {
														if (value == '1') {
															return "是";
														}
														return "否";
													}
												} ] ],
										pagination : true,
										onSelect : function(rowIndex, rowData) {
										},
										onUnselect : function() {
										},
										loadFilter : function(data) {
											// alert("inData:"
											// + JSON.stringify(data));
											return {
												total : data.totalElements,
												rows : data.content
											};
										},
										onBeforeLoad : function(param) {
											param.page -= 1;
											param.size = param.rows;
											delete param.rows;

											param.sort = 'CREATED_DATE desc';

											var bundleName = $('#txtBundleName')
													.val();
											if (bundleName != "") {
												param.bundleName = bundleName;
											}
										},
										onLoadError : function(e) {
											// alert(JSON.stringify(e));
											$.messager.alert('错误', '<p>'
													+ e.responseJSON.message
													+ '</p>',
													'error');
										}
									});

					$("#datagrid").datagrid('getPager').pagination({
						displayMsg : '当前显示从 [{from}] 到 [{to}] 共[{total}]条记录'
					});
					$(".panel-tool-close, #instance_cancel").click(function(e) {
						$("body").css("overflow-x", "inherit")
					});

				});
function search() {
	$("#datagrid").datagrid('reload');
}
function refresh() {
	$("#datagrid").datagrid('reload');
}
function start(bundleId) {
	executeBundle(bundleId, 'startBundle', '启动');
}
function stop(bundleId) {
	executeBundle(bundleId, 'stopBundle', '停止');
}
function uninstall(rowIndex) {
	$.messager.confirm('温馨提示', '<p>你真的要卸载么?</p>', function(result) {
		if (result) {
			var rowData = $('#datagrid').datagrid('getRows')[parseInt(rowIndex, 10)];
			if(rowData.isCore=='0'){
				$.messager.alert('错误', '<p>非内核Bundle只能在业务服务管理界面修改！</p>',
				'error');
				return;
			}
			executeBundle(rowData.id, 'uninstallBundle', '卸载');
		}
	});
}
function executeBundle(bundleId, url, msg) {
	var jsonData = {
		bundleId : bundleId
	};
	$
			.ajax({
				type : "get",
				url : BASE_URL_API + '/baseServiceManagement/' + url + '?v='
						+ Math.random(),
				dataType : 'json',
				data : jsonData,
				contentType : "application/json",
				success : function(data) {
					if (data.result == true) {
						$.messager.alert('提示', '<p>' + msg + '成功!</p>', 'info',
								function() {
									refresh();
								});
					} else {
						$.messager.alert('错误', '<p>' + data.msg + '</p>',
								'error');
					}
				},
				error : function() {
					$.messager.alert('错误', '<p>服务异常，' + msg
							+ '失败，请稍后重试或联系管理员!</p>', 'error');
				}
			});
}

// function showBundleDetail(bundleId) {
// alert(bundleId);
// window.location.href =
// "../ServiceGroupManagement/BundleDetail.html?bundleId="
// + bundleId + '&v=' + Math.random();
//
// }

function showBundleDetail(bundleId) {
	$("#datagridDetail")
			.datagrid(
					{
						url : BASE_URL_API
								+ '/baseServiceManagement/findBundleDetail?v='
								+ Math.random(),
						method : 'get',
						autoRowHeight : true,
						singleSelect : true,
						striped : true,
						nowrap : false,
						model : true,

						shadow : true,
						columns : [ [
								{
									field : 'id',
									title : 'Id',
									width : 10,
									align : 'center',
									styler : function(value, row, index) {
										return {
											style : 'vertical-align: top;'
										}
									}
								},
								{
									field : 'name',
									title : 'Bundle名称',
									width : 150,
									align : 'center',
									formatter : function(value, rowData,
											rowIndex) {
										var companent = '<div width="auto"><ul>';
										companent += '<li><div width="auto" float="left" align="left"><label style="align:left;">'
												+ value + '</label></div></li>';
										companent += '<br/><li>'
												+ createPropsTable(rowData.props)
												+ '</li>'
										companent += '</ul></div>';
										return companent;

									}
								}, {
									field : 'version',
									title : '版本',
									width : 10,
									align : 'center',
									styler : function(value, row, index) {
										return {
											style : 'vertical-align: top;'
										}
									}
								}, {
									field : 'category',
									title : '类别',
									width : 10,
									align : 'center',
									styler : function(value, row, index) {
										return {
											style : 'vertical-align: top;'
										}
									}
								}, {
									field : 'state',
									title : '状态',
									width : 10,
									align : 'center',
									styler : function(value, row, index) {
										return {
											style : 'vertical-align: top;'
										}
									}
								} ] ],
						pagination : false,
						loadFilter : function(data) {
							// alert("inData:"
							// + JSON.stringify(data));
							return {
								total : data.totalElements,
								rows : data.content
							};
						},
						onBeforeLoad : function(param) {
							param.page -= 1;
							param.size = param.rows;
							delete param.rows;
							param.bundleId = bundleId;
						}
					});
	$(".panel-tool-close, #instance_cancel").click(function(e) {
		$("body").css("overflow-x", "inherit")
	});
	$("#datagridDetail").datagrid('reload');
	$('#win').window('setTitle', 'Bundle详情');
	$('#win').window('open');

}
function createPropsTable(props) {
	if (props == null || props.length == 0) {
		return "";
	}
	var table = '<table width="150px">';
	// var regExpLt = new RegExp('<', 'g');

	var regBR = new RegExp(',  ', 'g');
	var regBR2 = new RegExp(', !! ', 'g');
	$
			.each(
					props,
					function(index, item) {
						var value = "";
						if(item.value instanceof Array)
						{
							for(var i = 0; i < item.value.length; i++)
							{
								value += item.value[i] + "<br/>";
							}
						}
						else
						{
							value = item.value + "";
						}
						value = value.replace(/&lt;/g, "<").replace(/&gt;/g, ">");
						value = value.replace(regBR, '<br/>');
						value = value.replace(regBR2, '<br/>');
						//value = value.replace(/,/g, "<br/>");
						value = value.replace(/href=\"([^\"])*\"/g, '');
						value = value.replace(/href=\'([^\'])*\'/g, '');
						value = value.replace(/<a/g, "<label");
						value = value.replace(/<\/a/g, "</label");
						var key = item.key + "";
						key = match(key);
						key = key.replace(/&lt;/g, "<").replace(/&gt;/g, ">");
						table += '<tr><td width="auto"  align="left"  valign="top"><label>'
								+ key
								+ '</label></td><td  align="left" style="word-wrap:break-word;word-break:break-all;"  width="200px" height="auto"><div align="left" style="height: auto; width: 730px;"><label>'
								+ value + '</label></div></td>';
					});
	table += "</table>"
	return table;
}
function match(value) {
	if (value == '' || value == null) {
		return "";
	}
	var substr = value.match("&lt;\\s*a.*&gt;.*&lt;/\\s*a.*&gt;");
	if (substr == null) {
		return value;
	}
	var sublv1 = substr + "";
	// sublv1 = sublv1.substring(0, sublv1.lastIndexOf(key) + key.length);
	var substr2 = sublv1.match("&gt;.*&lt;");
	if (substr2 == null) {
		return value;
	}
	var sublv2 = substr2 + "";
	// sublv2 = sublv2.substring(1, sublv2.length-1);
	sublv2 = sublv2.replace("&gt;", '');
	sublv2 = sublv2.replace("&lt;", '');
	var result = value.replace(sublv1, sublv2);
	return result;
}
function getUrlParam(name) {
	var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); // 构造一个含有目标参数的正则表达式对象
	var r = window.location.search.substr(1).match(reg); // 匹配目标参数
	if (r != null)
		return unescape(r[2]);
	return null; // 返回参数值
}

function openInstallBundle() {
	$('#import_link').window('setTitle', 'Bundle安装/更新');
	$('#import_link').window('open');
}
function installOrUpdateBundle() {
	var start = $('#cboxStart').is(':checked');
	var startLevel = $('#txtStartLevel').val();
	// alert(start + " " + startLevel);

	if ($("#file").val() == "") {
		$.messager.alert("警告", "<p>请选择需要上传的.jar格式的文件</p>", 'warning');
		return;
	}
	var tempArr = $("#file").val().split(".");
	var selFileType = tempArr[tempArr.length - 1];
	if (selFileType != "jar") {
		$.messager.alert("警告", "<p>选择的文件格式有误，请选择.jar格式的文件</p>", 'warning');
		return;
	}
	// alert("file name:"+$("#fileName").val());
	$("#buttons_inport .easyui-linkbutton").linkbutton("disable");
	$("#buttons_inport .l-btn-text").text("正在上传...");

	$.ajaxFileUpload({
		url : BASE_URL_API + '/baseServiceManagement/installOrUpdateBundle'
				+ '?name=' + encodeURI($("#fileName").val()) + '&start='
				+ encodeURI(start) + '&startLevel=' + encodeURI(startLevel),
		type : 'post',
		secureuri : false, // 一般设置为false
		fileElementId : 'file', // 上传文件的id、name属性名
		dataType : 'text', // 返回值类型，一般设置为json、application/json
		// data: "name=" + encodeURI($("#fileName").val()), //传递参数到服务器
		success : function(data, status) {
			// alert(JSON.stringify(data));
			// $("#fileName").val($('#file').val());
			var result = data.slice(data.indexOf(">") + 1, data.indexOf("</"));
			result = result + "";
			if (result.indexOf("1=") == 0) {
				$('#import_link').window('close');
				$.messager.alert('提示', "<p>"
						+ result.slice(result.indexOf("1=") + 2, result.length)
						+ "</p>", 'info');
			} else {
				$.messager.alert('错误', "<p>" + result + "</p>", "error");
			}
		},
		error : function(data, status, e) {
			alert(JSON.stringify(data));
			$.messager.alert('错误', "<p>安装/更新Bundle失败!</p>", "error");
		}
	});
}
function cancel() {
	$('#import_link').window('close');
}

var loading_point = {
	timer : null,
	len : 3,
	count : 0
};
function loading() {
	if (loading_point.count < loading_point.len) {
		loading_point.count++;
		$("#progressbar_point").text($("#progressbar_point").text() + ".");
	} else {
		loading_point.count = 0;
		$("#progressbar_point").text("");
	}
}
